package com.example.carrierapp.ui.main.waybill.arriveno

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.example.carrierapp.base.MVPBaseFragment
import com.example.carrierapp.bean.RowsBean
import com.example.carrierapp.bean.dispatch.CarFreeBean
import com.example.carrierapp.config.ConstValue
import com.example.carrierapp.config.gone
import com.example.carrierapp.config.show
import com.example.carrierapp.config.toast
import com.example.carrierapp.ui.adapter.CommonRecyclerAdapter
import com.example.carrierapp.ui.dialog.MAlertDialog
import com.example.carrierapp.ui.dialog.ModifyVolumeDialog
import com.example.carrierapp.ui.main.dispatch.search.DispatchSearchActivity
import com.example.carrierapp.ui.view.recycleview.HorizontalDividerDecoration
import com.example.carrierapp.ui.view.recycleview.WrapContentManager
import com.example.carrierapp.ui.view.recycleview.XRecyclerView
import com.example.carrierapp.util.DisplayUtil
import com.example.carrierapp.util.LogUtil
import com.example.carrierapp.util.ToastUtils
import com.example.carrierapp.viewmodel.itemmodel.ItemSearchModel
import com.example.carrierapp.viewmodel.itemmodel.ItemWaybillModel
import com.example.lb.fingerdemo.R
import com.google.gson.Gson
import kotlinx.android.synthetic.main.item_waybill_new.view.*
import kotlinx.android.synthetic.main.layout_recycleview.*
import kotlinx.android.synthetic.main.layout_search_bar.*

/**
 * 运单->运输中
 */
class WaybillArriveNoFragment : MVPBaseFragment<WaybillArriveNoContract.View, WaybillArriveNoPresenter>(), XRecyclerView.LoadingListener, WaybillArriveNoContract.View, ModifyVolumeDialog.OnVolumeClickListeber {
    private var mPage = 0
    private var mFilter = ""
    private var mLoadMore: Boolean = false
    private var tempItem: ItemWaybillModel? = null
    private var originCarNum: String? = null
    private val mModifyVolumeDialog by lazy { ModifyVolumeDialog(activity) }
    private val adapter by lazy {
        CommonRecyclerAdapter<ItemWaybillModel>(context, R.layout.item_waybill_new) { v, t, _ ->
            v.operation.setOnClickListener {
                if (t?.billState == 1) {
                    MAlertDialog.Builder(context)
                            .setTitle("确认撤销？")
                            .setMessage("您正在撤销运单${t.waybillCode}！")
                            .setPositiveButton("确认撤销") { _, _ ->
                                mPresenter.cancelWaybill(t.id)
                            }
                            .setNegativeButton("取消", null)
                            .create().show()
                } else {
                    if (t?.carrierSettlState == 3)
                        ToastUtils.showCenterToast(context, "结算中的运单不能修改")
                    else {
                        mModifyVolumeDialog.setOnVolumeClickListeber(this)
                        t?.let {
                            tempItem = it
                            originCarNum = it.carNumber
                            mModifyVolumeDialog.showDialogNotVolume(it.waybillCode, it.id, it.carNumber)
                        }
                    }
                }
            }
        }
    }

    override fun getLayout(): Int {
        return R.layout.fragment_waybill_arriveno
    }

    override fun initView() {
        super.initView()
        initRecycleView()
        et_dispatch_search.hint = "搜索装卸地/货主/司机/车牌/货名/编码"
    }

    override fun initData() {
        super.initData()
        showProgress()
        mPresenter.attachView(this)
        mPresenter.getWaybillList(mPage, mFilter)
    }

    override fun initEvent() {
        super.initEvent()
        ib_clear.setOnClickListener { et_dispatch_search?.setText("") }
        et_dispatch_search?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmpty(et_dispatch_search?.text.toString().trim { it <= ' ' })) {
                    ib_clear?.visibility = View.VISIBLE
                } else {
                    ib_clear?.visibility = View.GONE
                }
                mLoadMore = false
                mFilter = et_dispatch_search?.text.toString().trim { it <= ' ' }
                mPage = 0
                mPresenter.getWaybillList(mPage, mFilter)
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }

    private fun initRecycleView() {
        val mLinearLayoutManager = WrapContentManager(context, LinearLayoutManager.VERTICAL, false)
        recycler_view?.layoutManager = mLinearLayoutManager
        recycler_view?.addItemDecoration(HorizontalDividerDecoration(context, R.drawable.divider_horizontal_10_f3f6fa, DisplayUtil.dip2px(context, 10f)))
        recycler_view?.setLoadingMoreEnabled(true)
        recycler_view?.setPullRefreshEnabled(true)
        recycler_view?.setLoadingListener(this)
        recycler_view?.adapter = adapter
    }

    override fun onRefresh() {
        mFilter = ""
        mPage = 0
        mPresenter.getWaybillList(mPage, mFilter)
        mLoadMore = false
    }

    override fun onLoadMore() {
        mPage++
        mPresenter.getWaybillList(mPage, mFilter)
        mLoadMore = true
    }

    override fun createPresenter(): WaybillArriveNoPresenter {
        return WaybillArriveNoPresenter(context!!)
    }

    override fun getWaybillListSuccess(rows: RowsBean<ItemWaybillModel>) {
        dismissProgress()
        LogUtil.d("WaybillArriveNoFragment-getDispatchListSuccess-$rows")
        rows.items?.let {
            ll_empty.gone()
            if (mLoadMore) {
                recycler_view.loadMoreComplete()
                adapter.insertData(it)
            } else {
                recycler_view.refreshComplete()
                adapter.refresh(it)
            }
            recycler_view.setNoMore(it.size < 10)
            ll_empty?.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
        } ?: let {
            recycler_view.setNoMore(true)
            if (mLoadMore) {
                recycler_view.loadMoreComplete()
                ll_empty.gone()
            } else {
                recycler_view.refreshComplete()
                adapter.clear()
                ll_empty.show()
            }
        }
    }

    override fun getWaybillListFailde(msg: String) {
        dismissProgress()
        LogUtil.d("WaybillArriveNoFragment-getWaybillListFailde-$msg")
        ToastUtils.showCenterToast(msg, context)
        if (recycler_view != null) {
            recycler_view?.loadMoreComplete()
            recycler_view?.refreshComplete()
        }
        ll_empty?.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
    }

    override fun modifyVolumeSuccess(bean: String) {
        if (bean.isNullOrEmpty()) {
            ToastUtils.showCenterToast("修改成功", context)
            if (mModifyVolumeDialog.isShowing) {
                mModifyVolumeDialog.dismiss()
            }
        } else {
            MAlertDialog.Builder(activity)
                    .setTitle(tempItem?.waybillCode)
                    .setMessage(bean)
                    .setPositiveButton("确认变更") { _, _ ->
                        tempItem?.let {
                            mPresenter.modifyVolume(it.id, it.carNumber, true)
                        }
                    }
                    .setNegativeButton("取消", null)
                    .create().show()
        }
    }

    override fun modifyVolumeFailde(msg: String) {
        ToastUtils.showCenterToast(msg, context)
    }

    override fun cancelWaybillSuccess(bean: String) {
        ToastUtils.showCenterToast("撤销成功", context)
        onRefresh()
    }

    override fun cancelWaybillFailde(msg: String) {
        ToastUtils.showCenterToast(msg, context)
    }

    override fun onVolume(newVolume: String, carNum: String, id: Int) {
        if (originCarNum == carNum)
            ToastUtils.showCenterToast(context, "未修改任何数据")
        else {
            tempItem?.carNumber = carNum
            mPresenter.modifyVolume(id, carNum, false)
        }
    }

    override fun onCarNumClick() {
        val intent = Intent(context, DispatchSearchActivity::class.java)
        intent.putExtra(ConstValue.TYPE, DispatchSearchActivity.SEARCH_TYPE_CARNUM)
        startActivityForResult(intent, DispatchSearchActivity.SEARCH_TYPE_CARNUM)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            data?.let {
                val carInfo = Gson().fromJson(it.getStringExtra("info"), ItemSearchModel::class.java)
                LogUtil.d("onActivityResult-" + carInfo.id + "--" + carInfo.name)
                when (requestCode) {
                    DispatchSearchActivity.SEARCH_TYPE_CARNUM -> {
                        LogUtil.d("onActivityResult-" + carInfo.id + "--" + carInfo.name)
                        if (mModifyVolumeDialog.isShowing) {
                            mModifyVolumeDialog.setCarNum(carInfo.name)
                        }
                    }
                }
            }
        }
    }

    companion object {

        fun newInstance(): WaybillArriveNoFragment {
            return WaybillArriveNoFragment()
        }
    }
}
